package com.example.lib_base.base.mvp.presenter;

import com.example.lib_base.base.mvp.view.BaseMvpActivity;
import com.example.lib_base.base.mvp.view.BaseMvpFragment;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.FragmentEvent;

import java.lang.ref.WeakReference;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * @author yedong
 * @date 2019/1/11
 * mvp的P层基类
 */
public abstract class BasePresenter<V> implements Presenter<V> {

    protected WeakReference<V> mMvpView;  // 弱引用View

    protected BaseMvpActivity mActivity;
    protected BaseMvpFragment mFragment;

    public BasePresenter(BaseMvpActivity act){
        this.mActivity=act;
    }

    public BasePresenter(BaseMvpFragment frag){
        this.mFragment=frag;
    }

    @Override
    public void attachView(V view) {
        this.mMvpView = new WeakReference<>(view);
    }

    protected V getView() {
        return mMvpView.get();
    }

    @Override
    public void detachView() {
        if (mMvpView != null) {
            mMvpView.clear();
            mMvpView = null;
        }
    }

    /**
     * Activity网络请求通用方法
     *
     * @param observable
     * @param subscriber
     * @param <T>
     */
    protected  <T> void addActSubscribe(Observable<T> observable, DisposableObserver<T> subscriber ) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mActivity.<T>bindUntilEvent(ActivityEvent.DESTROY))//绑定生命周期，防止内存泄露
                .subscribe(subscriber);
    }

    /**
     * Fragment网络请求通用方法
     * @param observable
     * @param subscriber
     * @param <T>
     */
    protected  <T> void addFragSubscribe(Observable<T> observable,DisposableObserver<T> subscriber ) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(mFragment.<T>bindUntilEvent(FragmentEvent.DESTROY))//绑定生命周期，防止内存泄露
                .subscribe(subscriber);
    }
}
